<?php


namespace app\common\service\wechat;


use app\admin\model\bargain\Bargain;
use app\admin\model\bargain\BargainUserHelp;
use app\admin\model\store\GoodsSku;
use app\admin\model\user\User;
use app\admin\model\wx\WxAccount;
use app\admin\model\wx\WxFans;
use app\admin\model\wx\WxMedia;
use app\admin\model\wx\WxMediaInfo;
use app\admin\model\wx\WxReply;
use app\common\service\BaseService;
use app\common\service\lib\Tuling;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Image;
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\Kernel\Messages\Video;
use EasyWeChat\Kernel\Messages\Voice;
use think\facade\Log;

class WechatService extends BaseService
{

    /**
     * Author:YangXinPeng
     * 公众号服务入口
     * @throws \EasyWeChat\Kernel\Exceptions\BadRequestException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \ReflectionException
     */
    public static function toConfig()
    {
        $config = config("setting.wechat");
        $app = Factory::officialAccount($config);
        $app->server->push(function ($message)use($app) {
            switch ($message['MsgType']) {
                case 'event':
                    switch ($message['Event']) {
                        case "subscribe": // 关注公众号 添加关注回复
                            $user = $app->user->get($message['FromUserName']);
                            WxFans::create($user);
                            return '感谢关注';
                            break;
                        case "unsubscribe": // 取消关注公众号
                            $user = $app->user->get($message['FromUserName']);
                            $subscribe = $user['subscribe'];
                            $openId = $user['openid'];
                            $time = time();
                            WxFans::where('openid',$openId)->update([
                                'subscribe'=>$subscribe,
                                'unsubscribe_time'=>$time
                            ]);
                            WxFans::where('openid',$openId)->delete();
                            break;
                    }
                   // return '收到事件消息';
                    break;
                case 'text':
                    $result = WxReply::where('keyword','like',"%{$message['Content']}%")->select();
                    $result = $result->toArray();
                    if (count($result) > 0){
                        $result = $result[0];
                        switch ($result['msg_type']){
                            case 'text':
                                $content =new Text($result['data']);
                                $app->customer_service->message($content)->to($message['FromUserName'])->send();;
                                break;
                            case 'image':
                                $materialId = $result['material_id'];
                                $media_id = WxMedia::where('id',$materialId)->value('media_id');
                                $content = new Image($media_id);
                                $app->customer_service->message($content)->to($message['FromUserName'])->send();;
                                break;
                        }
                    } else {
                        $id=1;
                        $text = $message['Content'];
                        $tuling = new Tuling();
                        $tulingRes = $tuling->index($text, $id);
                        $content =new Text($tulingRes);
                        $app->customer_service->message($content)->to($message['FromUserName'])->send();
                    }
//                    return '收到文字消息';
                    break;
                case 'image':
                    return '收到图片消息';
                    break;
                case 'voice':
                    return '收到语音消息';
                    break;
                case 'video':
                    return '收到视频消息';
                    break;
                case 'location':
                    return '收到坐标消息';
                    break;
                case 'link':
                    return '收到链接消息';
                    break;
                case 'file':
                    return '收到文件消息';
                default:
                    return '收到其它消息';
                    break;
            }
        });
        $response = $app->server->serve();
        $response->send();
    }

    /**
     * Author:YangXinPeng
     * 获取关注回复
     * @return Image|News|Video|Voice|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getSubscribeReply()
    {
        $weixin_replay = new WxReply();
        $info = $weixin_replay->where('type', 'subscribe')
            ->find();
        if (!empty($info)) {
            $info = $this->getWeixinReplyDetail($info);
            return $info;
        } else {
            return $this->getWeixinReplyDefault();
        }
    }

    /**
     * Author:YangXinPeng
     * 默认回复
     * @return mixed
     */
    protected function getWeixinReplyDefault(){
        $message = WxReply::where('type','default')->value('data');
        return $message;
    }

    /**
     * Author:YangXinPeng
     * 根据订阅设置回复相应媒体类型
     * @param $info
     * @return Image|News|Video|Voice|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function getWeixinReplyDetail($info)
    {
        $msg_type = $info->msg_type;
        $material_id = $info->material_id;
        $media_id = '';
        if($material_id){
            $material = WxMedia::find($material_id);
            if($material){
                $media_id = $material->media_id;
            }
        }
        $message = WxReply::where('type','default')->value('data');
        switch ($msg_type) {
            case 'text':
                $message = $info->data;
                break;
            case 'keyword':
                $message = $info->data;
                break;
            case 'image':
                if(WxMedia::where('media_id',$media_id)->find()){
                    $message =  new Image($media_id);
                }
                break;
            case 'news':
                $new = WxMediaInfo::where('material_id', $material_id)->find();
                if ($new) {
                    $newsList[] = new NewsItem([
                        'title' => $new->title,
                        'description' => $new->digest,
                        'url' => $new->url,
                        'image' => $new->cover,
                    ]);
                    $message = new News($newsList);
                }
                break;
            case 'video':
                if(WxMedia::where('media_id',$media_id)->find()) {
                    $message =  new Video($media_id, [$material->file_name, $material->des]);
                }
                break;
            case 'voice':
                if(WxMedia::where('media_id',$media_id)->find()) {
                    $message =  new Voice($media_id);
                }
                break;
            default:
                break;
        }
        return $message;
    }

    /**
     * Author:YangXinPeng
     * 获取菜单
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public static function getList()
    {
        $config = [
            'app_id' => 'wx84bbd23ec0156a9e',
            'secret' => '3a511dc4d6a37306b79ebe3e8c50db40',
            'token' => '1812a',
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            //...
        ];
        $app = Factory::officialAccount($config);
        $current = $app->menu->list();
    }

    /**
     * Author:YangXinPeng
     * 删除菜单
     * @return mixed
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function delList()
    {
        $config = [
            'app_id' => 'wx84bbd23ec0156a9e',
            'secret' => '3a511dc4d6a37306b79ebe3e8c50db40',
            'token' => '1812a',
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            //...
        ];
        $app = Factory::officialAccount($config);
        $res =  $app->menu->delete();
        return $res;
    }

    /**
     * Author:YangXinPeng
     * 添加菜单
     * @param $menu
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function addList($menu)
    {
        $config = [
            'app_id' => 'wx84bbd23ec0156a9e',
            'secret' => '3a511dc4d6a37306b79ebe3e8c50db40',
            'token' => '1812a',
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            //...
        ];
        $app = Factory::officialAccount($config);
        $res = $app->menu->create($menu['button']);
        if ($res['errcode'] == 0){
            return self::success('添加成功');
        }else{
            return self::fail('添加失败');
        }
    }

    /**
     * Author:YangXinPeng
     * 获取当前公众号对菜单信息
     * @param $appid
     * @return array|mixed
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public static function changeApp($appid){
        $config = [
            'app_id' => 'wx84bbd23ec0156a9e',
            'secret' => '3a511dc4d6a37306b79ebe3e8c50db40',
            'token' => '1812a',
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            //...
        ];
        $app = Factory::officialAccount($config);
        $isAPP = WxAccount::where('app_id',$appid)->value('status');
        $button['button']=[];
        if(!$isAPP){
           return self::fail('失败');
        }
        $menu = $app->menu->list();
        return $menu;
    }

    /**
     * Author:YangXinPeng
     * 砍价模版通知
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function bargainNotice($params)
    {

        $config = config("setting.wechat");
        $app = Factory::officialAccount($config);
        $openId = User::where('id',$params['uid'])->value('wx_openid');

        $nickName = User::where('id',$params['bargain_user_help_id'])->value('nickname');
        $where=[];
        $where['subscribe'] = 1;
        $where['openid'] = $openId;
        $title = Bargain::where('id',$params['bargain_id'])->value('title');
        $total = Bargain::where('id',$params['bargain_id'])->value('bargain_num');
//        $fan = WxFans::where($where)->find();
        $sku = GoodsSku::with('goods')->where('id',$params['sku_id'])->find();

        $sku && $sku= $sku->toArray();

        $num = BargainUserHelp::where('bargain_id',$params['bargain_user_id'])->count();
//        if ($fan){
        try {
            $app->template_message->send([
                'touser' => $openId,
                'template_id' => 'ME4pZlelCTZ4P-mkc7CY0q78npFINUlAiZrWjv6HG_w',
                'url' => 'https://easywechat.org',
                'data' => [
                    //商品名称
                    'thing1' => $sku['goods_name'],
                    //砍价进度
                    'phrase2' => "$num/$total",
                    //砍价好友
                    'thing6'=>$nickName,
                    //活动名称
                    'thing5'=>$title
                ],
            ]);
        } catch (\Exception $exception){
            dd($exception->getMessage());
        }

//        }else{
//            Log::info('用户已取消订阅，推送失败');
//        }
    }


}